import React, { Component,PropTypes } from 'react';
import CommonBtn from '../../Component/CommonComponent/CommonBtn'
import '../../Stylesheets/wx/comfirmPayMoney.css';
import Location from '../../Component/SellerStore/Location'
import {ErrorNum,wechatTest,emptyTest,GetQueryString,saveToken,loadToken,getToken} from '../../Action/rpc'
import {context} from 'react-router'
import {authApply,authInfo,MyInfo,WxLogin,ApplyCheck} from '../../Action/auth';
import {WechatAuth} from '../../Action/autoLogin'
import UUID from 'uuid-js'
import DelayModal from '../../Component/CommonComponent/DelayModal'

export default class Authorization extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            name : '',
            mobile : '',
            wxAccName:'',
            address : '',
            street : '',
            detail : '',
            type : false,
            id : '',
            showMap:false,
            Reminder:'',
            provName:'',
            cityName:'',
            countysName:'',
            provId:'',
            cityId:'',
            countyId:'',
            accIdImg:require("../../Images/uploadImg.png"),
            accIdImgUp:'',
            recommendId:0,
            grade:0,
            modalDelay:false,
            upState:false
        };
        this.click = true;
    }

    async componentWillMount() {
        let recommendId = GetQueryString('recommendId')?GetQueryString('recommendId'):0;
        if( GetQueryString('recommendId')){
            sessionStorage.setItem('recommendId',recommendId)
        }else{
            recommendId = sessionStorage.getItem('recommendId')
        }

        //sessionStorage.setItem('recommendId',recommendId)
        const uri = window.location.href;
        this.setState({
            recommendId:recommendId
        })

        if(sessionStorage.getItem('isChat')){
            if(GetQueryString('code') && !loadToken() ){
                await this.getLoginToken(GetQueryString('code'))
            }
        }else{
            const getToken = loadToken();
            if(getToken == '' ||getToken == null ||getToken == 'null'){
                sessionStorage.setItem('isChat',true)
                //await WechatAuth(uri)
                return
            }
        }
        //await this.getMyInfo();

    }
    async getMyInfo(){
        await MyInfo()
            .then(res=>{
                sessionStorage.setItem('myAgent',res.AGENT_GRADE);
                if(res.AGENT_GRADE>0){
                    if(res.IS_ACTIVE ==1){
                        alert('申请代理成功，请前往进货')
                        this.context.router.push({pathname:'/purchase'})
                    }else{
                        alert('您已经是代理，请返回个人中心')
                        this.context.router.push({pathname:'/personalCenter'})
                    }
                }else{
                    this.getApplyCheck()
                }
            })
    }

    async getApplyCheck(){
        await ApplyCheck()
            .then(res=>{
                if(res==1){
                    alert('您已提交过资料，请前往申请等级')
                    this.context.router.push({pathname:'/agentGrade'})
                }
                console.log(res)
            })
            .catch(err=>{
                alert(err.message)
                console.log(err)
            })
    }

    async getLoginToken(code){
        await WxLogin(code)
            .then(res=>{
                const token = res.token;
                sessionStorage.setItem('openId',res.openId)
                saveToken(token)
            })
            .catch(err=>{
                alert(err.message)
                console.log(err)
            })
    }

    static contextTypes = {
        router:PropTypes.object
    }

    //得到地址信息
    async getValue(provName,cityName,countysName,prov,city,county){
        //改变默认值
        if(prov == '110000' || prov =='120000' || prov =='310000' || prov =='500000'){
            //改变初始化的内容
            if((provName == ''|| provName == null) && (countysName != '' || countysName != null)
                && countysName != undefined)
            {
                await this.setState({provName:'北京市',cityName:'',countysName:countysName,provId:'110000',
                    cityId:'0',countyId:county,showMap:false})
                this.setState({address:this.state.provName+''+this.state.cityName+this.state.countysName});
                return
            }
            if(countysName == '' || countysName == null || countysName== undefined){
                alert('请选择对应的城市和区县')
                return
            }
            if((provName != ''|| provName != null) && (county != '' || county != null)){
                await this.setState({provName:provName,cityName:'',countysName:countysName,provId:prov,
                    cityId:'0',countyId:county,showMap:false
                });
                this.setState({address:this.state.provName+''+this.state.cityName+this.state.countysName});
                return
            }

        }else if(prov == '710000' || prov =='810000' || prov =='820000'){
            await this.setState({provName:provName,cityName:'',countysName:'',provId:prov,cityId:'0',
                countyId:'0',showMap:false
            });
            this.setState({address:this.state.provName+''+this.state.cityName+this.state.countysName});
            return
        }else if(prov != '' && city != '' && county != ''){
            await this.setState({
                provName:provName,
                cityName:cityName,
                countysName:countysName,
                showMap:false,
                provId:prov,
                cityId:city,
                countyId:county,
            })
            this.setState({address:this.state.provName+this.state.cityName+this.state.countysName})
        }else{
            alert('地址请选择完整')
        }
    }


    fileChange (type,e){
        //const {accIdImgUp,accIdImgFile}=this.state
        this.setState({modalDelay:true})
        var file = e.target.files[0];
        var fileName = window.URL.createObjectURL(file);
        var index1=file.name.lastIndexOf(".");
        var index2=file.name.length;
        var suffix=file.name.substring(index1,index2);
        console.log(suffix);
        var uuid4 = UUID.create().toString();
        console.log(uuid4.toString());
        var storeAs = 'sq/'+uuid4+''+suffix;
        console.log(file.name + ' => ' + storeAs);

        let ossup=[{'storeAs':storeAs,'file':file}];
        const client = new OSS.Wrapper({
            region: 'oss-cn-shanghai',
            accessKeyId: 'LTAIbrSAT1OgIEDo',
            accessKeySecret: 'rOI5hYbqCTy3B2sb6Zbt77Is9h34XS',
            bucket: "shyt-image"
        });
        ossup.map((el,index)=>{
            client.multipartUpload(el.storeAs,el.file).then((result)=> {
                if(type==1){
                    this.setState({
                        accIdImg:fileName,
                        accIdImgUp:storeAs,
                        accIdImgFile:file

                    })
                }else{
                    this.setState({
                        payImg:fileName,
                        payImgUp:storeAs,
                        payImgFile:file
                    })
                }
                this.setState({upState:true})
                this.setState({modalDelay:false})
                console.log(result.url);
            }).catch(function (err) {
                console.log(err);
                this.setState({modalDelay:false})
                this.setState({upState:false})
                return false
            })
        })

    }


    submit (ev){
        if(this.click){
            //recommendId,accIdImg,name,mobile,wxAccName,province,city,area
            //this.context.router.push({pathname:'/buyFirst'})
            const {recommendId,accIdImgUp,accIdImgFile,provName,cityName,countysName,address,upState}=this.state
            //ev.preventDefault();
            this.click = false;
            if(this.refs.name.value==''){
                this.setState({Reminder:'姓名不能为空'})
                this.click = true;
                return
            }else if(this.refs.mobile.value==''){
                this.setState({Reminder:'手机号不能为空'})
                this.click = true;
                return
            }else if(!ErrorNum(this.refs.mobile.value)){
                this.setState({Reminder:'手机号码有误,请重新填写'})
                this.click = true;
                return
            }else if(address==''){
                this.setState({Reminder:'地址不能为空'})
                this.click = true;
                return
            }else if(this.refs.accIdImg.value==''){
                this.setState({Reminder:'请上传图片'})
                this.click = true;
                return
            }else{
                this.setState({Reminder:''})
                //let ossup=[{'storeAs':accIdImgUp,'file':accIdImgFile}];
                //let upState = true;
                //const client = new OSS.Wrapper({
                //    region: 'oss-cn-shanghai',
                //    accessKeyId: 'LTAIbrSAT1OgIEDo',
                //    accessKeySecret: 'rOI5hYbqCTy3B2sb6Zbt77Is9h34XS',
                //    bucket: "shyt-image"
                //});
                //ossup.map((el,index)=>{
                //    client.multipartUpload(el.storeAs,el.file).then((result)=> {
                //        console.log(result.url);
                //    }).catch(function (err) {
                //        console.log(err);
                //        upState=false;
                //        return false
                //    })
                //})

                if(upState){
                    this.setState({modalDelay:true})
                    //recommendId,accIdImg,name,mobile,wxAccName,province,city,area
                    authApply(
                        recommendId?recommendId:0,
                        this.state.accIdImgUp,
                        this.refs.name.value,
                        this.refs.mobile.value,
                        provName,
                        cityName!=''?cityName:'直辖市',
                        countysName
                    )
                        .then(res=>{
                            alert('提交成功，请选择代理等级')
                            this.click = true;
                            this.context.router.push({pathname:'/agentGrade'})
                            this.setState({modalDelay:false})
                        })
                        .catch(err=>{
                            alert(err)
                            console.warn('提交失败',err)
                            this.click = true;
                            this.setState({modalDelay:false})
                        })
                }else{
                    this.click = true;
                }
            }
            /*if(this.refs.accIdImg.value!=''
                &&this.refs.name.value!=''
                &&address!=''
                &&ErrorNum(this.refs.mobile.value)){
                let ossup=[{'storeAs':accIdImgUp,'file':accIdImgFile}];
                let upState = true;
                const client = new OSS.Wrapper({
                    region: 'oss-cn-shanghai',
                    accessKeyId: 'LTAIbrSAT1OgIEDo',
                    accessKeySecret: 'rOI5hYbqCTy3B2sb6Zbt77Is9h34XS',
                    bucket: "shyt-image"
                });
                ossup.map((el,index)=>{
                    client.multipartUpload(el.storeAs,el.file).then((result)=> {
                        console.log(result.url);
                    }).catch(function (err) {
                        console.log(err);
                        upState=false;
                        return false
                    })
                })

                if(upState){
                    //recommendId,accIdImg,name,mobile,wxAccName,province,city,area
                    authApply(
                        recommendId?recommendId:0,
                        this.state.accIdImgUp,
                        this.refs.name.value,
                        this.refs.mobile.value,
                        provName,
                        cityName!=''?cityName:'直辖市',
                        countysName
                    )
                        .then(res=>{
                            alert('提交成功，请选择代理等级')
                            this.click = true;
                            this.context.router.push({pathname:'/agentGrade'})
                        })
                        .catch(err=>{
                            alert(err)
                            console.warn('获取资料失败',err)
                            this.click = true;
                        })
                }else{
                    this.click = true;
                }

            }else{
                alert('请填写全部内容与上传图片')
                this.click = true;
            }*/
        }

    }
/*    async submit(){
        //recommendId,accIdImg,name,mobile,wxAccName,agentId,province,city,area
        const {name,mobile,address,detail,type,id,provId,cityId,countyId} = this.state
        console.log('新增地址',address)
       /!* if (!ErrorNum(mobile)) {
            this.setState({Reminder:'手机号码有误,请重新填写'})
            return
        }

        if(!name || !mobile  || !address  || !detail){
            this.setState({Reminder:'所填数据不能为空。。。'})
            return
        }else{
            this.setState({Reminder:''})
        }*!/

        this.context.router.push({pathname:'/agentGrade'})


    }*/

    render() {
        const {showMap,address,accIdImg} = this.state
        return (
            <div className="containerNav">
                <div className="flex flex-pack-justify flex-align-center border_bottom f14" style={{height:50,padding:'0 10px'}}>
                    <div className="color6">姓名</div>
                    <div className="color9">
                        <input
                            ref = 'name'
                            className="borderno tr "
                            type="\"
                            placeholder="您的姓名"
                            onChange={()=>this.setState({name:this.refs.name.value})}
                        />
                    </div>
                </div>
                <div className="flex flex-pack-justify flex-align-center border_bottom f14" style={{height:50,padding:'0 10px'}}>
                    <div className="color6">联系电话</div>
                    <div className="color9">
                        <input
                            maxLength="11"
                            ref = 'mobile'
                            className="borderno tr"
                            type="\"
                            placeholder="电话号码"
                            onChange={()=>this.setState({mobile:this.refs.mobile.value})}
                        />
                    </div>
                </div>
                {/*<div className="flex flex-pack-justify flex-align-center border_bottom f14" style={{height:50,padding:'0 10px'}}>
                    <div className="color6">微信号</div>
                    <div className="color9">
                        <input
                            maxLength="11"
                            ref = 'wxAccName'
                            className="borderno tr"
                            type="\"
                            placeholder="微信号"
                            onChange={()=>this.setState({wxAccName:this.refs.wxAccName.value})}
                        />
                    </div>
                </div>*/}
                <div
                    className="flex flex-pack-justify flex-align-center border_bottom f14" style={{height:50,padding:'0 10px'}}
                    onClick = {()=>this.setState({showMap:true})}
                >
                    <div className="color6">所在地区</div>
                    <div className="color9">
                        {address}
                    </div>
                </div>
                <div className="flex flex-pack-justify flex-align-center border_bottom f14" style={{height:100,padding:'0 10px'}}>
                    <div className="color6">上传手持身份证照</div>
                    <div className="di posr width100 flex flex-pack-center" style={{width:80,height:80,overflow:'hidden'}}>
                        <input
                            type="file"
                            className='uploadFileInput'
                            onChange={(e)=>this.fileChange(1,e)}
                            ref="accIdImg"
                        />
                        <img src={accIdImg} style={{height:'100%',width:'100%'}} />
                    </div>
                </div>
                {/*<div className="width80 center paddingTb5 " style={{display:'block'}}>
                    <p className="f12">上传手持身份证照</p>
                    <div className="pAll bkr_Tr borderPink">
                        <div className="di posr width100 flex flex-pack-center">
                            <input
                                type="file"
                                className='uploadFileInput'
                                onChange={(e)=>this.fileChange(1,e)}
                                ref="accIdImg"
                            />
                            <img src={accIdImg} style={{height:80,width:'auto'}} />
                        </div>
                        <p className="colorfff f12 tc mt5 mb0">请确保手持身份证照姓名、身份证号清晰可见</p>
                    </div>
                </div>*/}
                <div className="tc f12 color_red width100 plr mtb" style={{height:36,lineHeight:'36px'}}>
                    {this.state.Reminder}
                </div>
                <CommonBtn
                    onClick={(e)=>this.submit(e)}
                    title={'确定'}
                />
                {
                    showMap?
                        <div className="locationModal pa width100 f14 flex flex-v" style={{zIndex:100}}>
                            <div
                                className="shadowNav flex-1"
                            >
                            </div>
                            <div className="bkg_color width100">
                                <Location
                                    getInfomation = {(provName,cityName,countysName,prov,city,county)=>
                                        this.getValue(provName,cityName,countysName,prov,city,county
                                    )}
                                    hiddenModal = {()=>this.setState({showMap:false})}
                                    options= {{
                                        prov:'110000',
                                        city:'110100',
                                        county:'0',
                                        defaultText:['省份','城市','区县']
                                    }}
                                />
                            </div>
                        </div>
                        :null
                }
                {
                    this.state.modalDelay?
                        <DelayModal />
                        :null

                }
            </div>
        );
    }
}
